﻿using System;
using System.Collections.Generic;
using System.Management.Automation;
using ITSP.SharePoint.CacheRefresh.Interfaces;
using ITSP.SharePoint.CacheRefresh.Repositories;
using Microsoft.Practices.SharePoint.Common.ServiceLocation;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.PowerShell;

namespace ITSP.SharePoint.CacheRefresh.PowerShell
{
    /// <summary>
    /// Updates the Cache Timer Jobs 
    /// </summary>
    [Cmdlet("Update", "ITSPCacheConfigTimerJobs", SupportsShouldProcess = true)]
    public class UpdateCacheConfigTimerJobs : SPSetCmdletBase<string>
    {
        #region Cmdlet Parameters
        [Parameter(Mandatory = true, HelpMessage = "The Url of the SharePoint Web Application that is hosting the Cache Configuration List")]
        public string Url;

        #endregion

        protected override bool RequireUserFarmAdmin()
        {
            return false;
        }

        protected override bool RequireLocalFarmExist()
        {
            return true;
        }


        protected override void UpdateDataObject()
        {
            #region validation stuff

            // ensure can hit farm
            SPFarm farm = SPFarm.Local;
            if (farm == null)
            {
                ThrowTerminatingError(new InvalidOperationException("SharePoint farm not found."), ErrorCategory.ResourceUnavailable, this);
                SkipProcessCurrentRecord();
            }

            #endregion

            string cacheHostUrl = Url;
           
            Uri cacheHostUri = new Uri(cacheHostUrl);

            using (SPSite site = new SPSite(cacheHostUri.ToString()))
            {
                if (!site.RootWeb.Exists)
                {
                    WriteObject(String.Format("Cannot find SPWeb at {0}", cacheHostUri.LocalPath));
                }

                ICacheRefreshManager cacheRefreshManager = new CacheRefreshManager(cacheHostUri.ToString());
                cacheRefreshManager.RebuildCacheTimerJobs();

                using (ICacheConfigurationRepository repository = new SPCacheConfigurationRepository(cacheHostUri.ToString()))
                {
                    IList<ICacheConfigItem> listConfigItems = repository.GetAll();
                    foreach (ICacheConfigItem configItem in listConfigItems)
                    {
                        WriteObject(configItem);
                    }
                        
                }
                    
            }
            

        }
        
    }

    /// <summary>
    /// Adds a Cache Timer Job
    /// </summary>
    [Cmdlet(VerbsCommon.Add, "ITSPCacheConfigItem", SupportsShouldProcess = true)]
    public class AddCacheConfigItem : SPSetCmdletBase<string>
    {
        #region Cmdlet Parameters

        [Parameter(Mandatory = true, HelpMessage = "The Web Application Url")]
        [ValidateNotNullOrEmpty]
        public string Url;

        [Parameter(Mandatory = true, HelpMessage = "The Cache Key for the Cache Configuration")]
        [ValidateNotNullOrEmpty]
        public string CacheKey;

        [Parameter(Mandatory = true, HelpMessage = "The Cache Key for the Cache Configuration")]
        [ValidateNotNullOrEmpty]
        public string Description;

        [Parameter(Mandatory = true, HelpMessage = "The Path to the File Dependency e.g c:\\program files\\financial ombudsman service\\e-File Cache\\cache.cache")]
        [ValidateNotNullOrEmpty]
        public string DependencyFilePath;

        [Parameter(Mandatory = true, HelpMessage = "The interval between each cache invalidation is run. 0=never.")]
        [ValidateNotNullOrEmpty]
        public int CacheInterval;

        [Parameter(Mandatory = true, HelpMessage = "Should the cache be enabled?")]
        [ValidateNotNullOrEmpty]
        public bool CacheEnabled;

        #endregion

        protected override bool RequireUserFarmAdmin()
        {
            return false;
        }

        protected override bool RequireLocalFarmExist()
        {
            return true;
        }


        protected override void UpdateDataObject()
        {
            #region validation stuff

            // ensure can hit farm
            SPFarm farm = SPFarm.Local;
            if (farm == null)
            {
                ThrowTerminatingError(new InvalidOperationException("SharePoint farm not found."), ErrorCategory.ResourceUnavailable, this);
                SkipProcessCurrentRecord();
            }

            #endregion

            using (ICacheConfigurationRepository repository = new SPCacheConfigurationRepository(Url))
            {
                ICacheConfigItem configItem = repository.Add(CacheKey, Description, DependencyFilePath, CacheInterval, CacheEnabled);
                CacheRefreshManager cacheRefreshManager = new CacheRefreshManager(Url);
                cacheRefreshManager.RebuildCacheTimerJobs();
                WriteObject(configItem);
            }
        }

    }

    /// <summary>
    /// Remove a Cache Timer Job
    /// </summary>
    [Cmdlet(VerbsCommon.Remove, "ITSPCacheConfigItem", SupportsShouldProcess = true)]
    public class RemoveCacheConfigItem : SPSetCmdletBase<string>
    {
        #region Cmdlet Parameters

        [Parameter(Mandatory = true, HelpMessage = "The Web Application Url")]
        [ValidateNotNullOrEmpty]
        public string Url;

        [Parameter(Mandatory = true, HelpMessage = "The Cache Key for the Cache Configuration")]
        [ValidateNotNullOrEmpty]
        public string CacheKey;

        #endregion

        protected override bool RequireUserFarmAdmin()
        {
            return false;
        }

        protected override bool RequireLocalFarmExist()
        {
            return true;
        }


        protected override void UpdateDataObject()
        {
            #region validation stuff

            // ensure can hit farm
            SPFarm farm = SPFarm.Local;
            if (farm == null)
            {
                ThrowTerminatingError(new InvalidOperationException("SharePoint farm not found."), ErrorCategory.ResourceUnavailable, this);
                SkipProcessCurrentRecord();
            }

            #endregion

            using (ICacheConfigurationRepository repository = new SPCacheConfigurationRepository(Url))
            {
                if(repository.Delete(CacheKey))
                {
                    CacheRefreshManager cacheRefreshManager = new CacheRefreshManager(Url);
                    cacheRefreshManager.RebuildCacheTimerJobs();
                }
                
            }
        }

    }

    
}
